<template>
  <div>
    <van-index-bar :index-list="computedList" @select="handleChange">  <!--将索引字符状态赋值给索引字符列表-->
      <div v-for="data in cityList" :key="data.type">
        <van-index-anchor :index="data.type" />
        <van-cell v-for="city in data.list" :key="city.cityId" :title="city.name" @click="handleClick(city)" />
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import http from '@/util/http'
import { Toast } from 'vant'
import obj from '@/util/mixinObj'

export default {
  mixins: [obj],
  data () {
    return {
      cityList: [], // 通过字母排序好的城市名状态
      indexlist: [] // 索引字符状态
    }
  },

  computed: {
    computedList () {
      return this.cityList.map(res => res.type)
    }
  },

  mounted () {
    http({
      url: '/gateway?k=5340598',
      headers: {
        'X-Host': 'mall.film-ticket.city.list'
      }
    }).then(res => {
      // console.log(res.data.data.cities)
      this.cityList = this.renderCity(res.data.data.cities)
      // console.log(this.cityList)
      // console.log(newindex)
    })
  },

  methods: {
    handleChange (data) {
      // console.log('handleChange',data)
      Toast(data)
    },

    renderCity (list) {
      // console.log(list)
      const cityList = []
      const letterList = []
      for (let i = 65; i < 91; i++) {
        letterList.push(String.fromCharCode(i))
      }

      // console.log(letterList)
      letterList.forEach(letter => {
        const newList = list.filter(item => item.pinyin.substring(0, 1).toUpperCase() === letter)
        // console.log(newList)

        newList.length > 0 && cityList.push({ type: letter, list: newList }) // 前面条件不成立时，就不会理会后面的语句。

        // console.log(this.cityList)
      })

      return cityList
    },

    handleClick (city) {
      // console.log(city.name, city.cityId)
      // console.log(this.$store.state)
      // this.$store.state.cityName = city.name
      // this.$store.state.cityId = city.cityId
      this.$store.commit('changeCityName', city.name)
      this.$store.commit('changeCityId', city.cityId)
      this.$router.back()
      // this.$router.push('/films/nowplaying')
    }
  }
}
</script>

<style lang="scss">
.van-toast--text {
  width: -webkit-fit-content;
  width: fit-content;
  min-width: 30px;
  min-height: 0;
  padding: 8px 12px;
}
</style>
